<!--ChengXY 20230630-->
<!--文件上传列表组件-->
<template>
  <div>
    <el-table class="publicTable" :data="newTableData" style="overflow-y: scroll;border: 1px solid #e6ebf5;" border v-loading="loading">
      <el-table-column :show-overflow-tooltip="true">
        <template slot="header" slot-scope="{}" v-if="col.isReadOnly==1?false:true">
          <el-row :gutter="5">
            <el-col :span="1.5">
              <el-upload class="upload-demo" :action="url" :headers="headers" :accept="col.exts" :before-upload="uploadBefore" :on-success="uploadSuccess" :on-error="uploadError" multiple>
                <el-button size="mini"><i class="el-icon-upload"></i> 本地文件上传</el-button>
              </el-upload>
            </el-col>
          </el-row>
        </template>
        <el-table-column :show-overflow-tooltip="true" prop="fullName" label="文件名">
          <template slot-scope="scope">
            <div style="line-height: 14px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
              <span v-if="ifImg(scope.row.ext)">
                <!-- ***后台提供缩略图 -->
                <el-image :src="require('@/assets/icons/'+'Application/picture.png')" slot="prefix" :icon-class="scope.row.icon" style="width: 16px;" />
              </span>
              <!-- ***文档类型需要确认种类 -->
              <span v-else-if="(scope.row.ext=='doc'||scope.row.ext=='docx'||scope.row.ext=='xlsx'||scope.row.ext=='xls'||scope.row.ext=='pdf')&&(scope.row.icons && scope.row.icons[0]!=null)">
                <!-- TODO 注销 scope.row.icons[0].icon报错 -->
                <!-- <el-image :src="require('@/assets/icons/'+scope.row.icons[0].icon)" slot="prefix" :icon-class="scope.row.icon" style="width: 16px;" /> -->
              </span>
              <span v-else>
                <el-image :src="require('@/assets/icons/'+'Application/file.png')" slot="prefix" :icon-class="scope.row.icon" style="width: 16px;" />
              </span>
              {{ scope.row.fullName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="size" label="文件大小" min-width="40">
          <template slot-scope="scope">
            <span>{{getLateSize(scope.row.size)}}</span>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="ext" label="文件类型" min-width="40"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="createUser" label="上传人" min-width="40"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="createTime" label="上传时间" min-width="100"></el-table-column>
        <el-table-column  label="操作" min-width="80" fixed="right">
          <template slot-scope="scope">
            <el-button @click="lookOver(scope.row)" type="text" size="small">查看</el-button>
            <el-button @click="downloadFile(scope.row)" type="text" size="small">下载</el-button>
            <el-button type="text" size="small" @click="deleteFile(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <pagination v-show="total/queryParams.pageSize>1" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getFiles" />
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { delFile, listFile, downloadFile, fileView } from "@/api/form/file";

export default {
  name: 'publicTable',
  props: {
    // 需要的参数
    col: {
      type: Object,
      required: false,
      default: () => { }
    },
    partId: {
      type: String,
      required: false,
      default: ""
    },
    refType: {
      type: String,
      required: false,
      default: ""
    },
    fieldId: {
      type: String,
      required: true,
      default: ""
    }
  },
  data () {
    return {
      // 遮罩层
      loading: true,
      url: process.env.VUE_APP_BASE_API + '/file/upload?refId=' + this.partId + '&refType=' + this.refType + '&fieldId=' + this.fieldId,
      headers: {
        Authorization: "Bearer " + getToken()
      },
      originalTableData: [],
      newTableData: [],
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,/*
                    converterPath: null,
                    converterStatus: null,
                    converterHtmlPath: null,
                    ext: null,
                    size: null,
                    fullName: null,
                    name: null,*/
        partId: null,
        /*relativePath: null,
        uploadtypeId: null,*/
        fieldId: null,
        /* thumb: null,
         md5: null,
         partVersion: null,
         solred: null,
         remarks: null,
         sortNum: null,
         createUser: null,
         updateUser: null,*/
      },
    };
  },
  created () {
    this.getFiles();
  },
  watch: {
    partId: {
      handler (n, o) {
        this.url=process.env.VUE_APP_BASE_API + '/file/upload?refId=' + n + '&refType=' + this.refType + '&fieldId=' + this.fieldId;
        this.getFiles()
      }
    },
  },
  methods: {
    // 获取最后文件大小
    getLateSize (size) {
      var data = "";
      if (size < 0.1 * 1024) { //如果小于0.1KB转化成B
        data = size.toFixed(2) + "B";
      } else if (size < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
        data = (size / 1024).toFixed(2) + "KB";
      } else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
        data = (size / (1024 * 1024)).toFixed(2) + "MB";
      } else { //其他转化成GB
        data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
      }
      return data
    },
    ifImg (ext) {
      let res = false
      let types = "bmp，jpg，png，tif，gif，pcx，tga，exif，fpx，svg，psd，cdr，pcd，dxf，ufo，eps，ai，raw，wmf, jpeg"
      if (types.indexOf(ext) != -1) {
        res = true
      }
      return res
    },
    // 转换状态
    getState (state) {
      let s = "";
      if (state == "0") {
        s = "未转换";
      } else if (state == "1") {
        s = "转换成功";
      } else if (state == "-1") {
        s = "转换失败";
      }
      return s;
    },
    getFiles () {
      // 新增 空数据
      this.queryParams.partId = this.partId;
      this.queryParams.fieldId = this.fieldId;
      listFile(this.queryParams).then(response => {

        if(response){
         this.newTableData = response.rows.length == 0 ? [] : response.rows;
         this.total = response.total;
         this.loading = false

         console.log('this.newTableData', this.newTableData);
       }else{
         this.newTableData =  [] ;
         this.total = 0;
         this.loading = false
       }
      })
    },
    uploadError () {
      this.$message.error('上传文件异常！');
    },
    uploadSuccess (response, file, fileList) {
      console.log('uploadSuccess', response);
      if (response.code === 200) {
        this.$message({
          message: '上传文件成功！',
          type: 'success'
        });
        this.getFiles()
      }
    },
    uploadBefore(file){
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.'));

      console.log('uploadBefore - col', this.col);

      //  兼容未限制格式类型
      const whiteList = this.col.exts

      if (whiteList) {
        const whiteListArray = whiteList.split(',');
        const isSuffix = whiteListArray.indexOf(fileSuffix.toLowerCase()) === -1 && whiteListArray.indexOf('.*') === -1
        if (isSuffix) {
          this.$message.error('上传文件只能是['+whiteList +']格式');
          return false;
        }
      }

      return true;
    },
    handleClick (row) {
      console.log(row);
    },
    // 删除文件
    deleteFile (file) {
      this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delFile(file.id).then(r => {
          if (r.code === 200) {
            this.newTableData = this.newTableData.filter(l => {
              return l.id !== file.id;
            });
            this.$emit('change', {
              list: this.newTableData,
              fieldId: this.col.fieldId
            });
            this.$message({
              message: '删除文件成功！',
              type: 'success'
            });
          }
        })
      })
    },
    // 下载文件
    downloadFile (file) {
      downloadFile(file.id).then(response => {
        console.log(response)
      })
    },
    // 查看文件
    lookOver (file) {
      fileView(file.id).then(response => {
        window.open(response.data);
      })
    }
  }

}

</script>
<style >
::v-deep .el-table--medium .el-table__cell {
  padding: 5px 0;
}
[data-v-5c162857] .el-upload-list {
  display: none!important;
}
</style>
